package com.lslx.ln.sample.api.customer;

import com.lslx.ln.sample.DemoService;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;

/**
 * <pre>
 *  Application
 * </pre>
 *
 * @Author zhangj
 * @Date 2022/6/26 18:41
 */
public class Application {

    public static void main(String[] args) {
        if(isClassic(args)) {
            startWithRefer();
        } else {
            startWithBootstrap();
        }
    }

    private static void startWithBootstrap() {
        ReferenceConfig<DemoService> reference = new ReferenceConfig<>();
        reference.setInterface(DemoService.class);
        reference.setGeneric("true");

        DubboBootstrap bootstrap = DubboBootstrap.getInstance();
        bootstrap.application(new ApplicationConfig("dubbo-demo-api-consumer"))
                .registry(new RegistryConfig("zookeeper://127.0.0.1:2181"))
                .reference(reference)
                .start();

        DemoService demoService = ReferenceConfigCache.getCache().get(reference);
        String message = demoService.sayHello("dubbo");
        System.out.println(message);

        GenericService genericService = (GenericService) demoService;
        Object sayHello = genericService.$invoke("sayHello", new String[]{String.class.getName()}, new Object[]{"dubbo generic invoke"});
        System.out.println(sayHello);

    }

    private static void startWithRefer() {
        ReferenceConfig<DemoService> reference = new ReferenceConfig<>();
        reference.setInterface(DemoService.class);

        reference.setApplication(new ApplicationConfig("dubbo-demo-api-consumer"));
        reference.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        DemoService demoService = reference.get();
        String message = demoService.sayHello("dubbo");
        System.out.println(message);
    }

    private static boolean isClassic(String[] args) {
        return args.length > 0 && "classic".equalsIgnoreCase(args[0]);
    }

}
